﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using app.Models;
using AmuTools;
using app.Common.recommendUtil;
using System.Data;

namespace app.Api
{
    /*
        投资模块
    */
    public class ApiService : ApiBase
    {
        public ApiService(Controller ctx) : base(ctx) { }

        #region 时间参数
        string create_time { get { return GetStringParam(new ReqStringParamOption { Name = "create_time" }); } }
        #endregion

        public void Do(string action)
        {
            switch (action)
            {
                case "page":
                    {
                        // condition 条件拼接
                        string name = GetStringParam(new ReqStringParamOption { Name = "name", Level = REQPARAMLEVEL.FREE });
                        string number = GetStringParam(new ReqStringParamOption { Name = "number", Level = REQPARAMLEVEL.FREE });
                        Cd cd = new Cd();
                        cd.And("member_id='{0}'", UserCode);
                        if (req_status != 6)
                        {
                            cd.And("status='{0}'", req_status);
                        }
                        if (name != "")
                        {
                            cd.And("title like '%{0}%'", name);
                        }
                        if (number != "")
                        {
                            cd.And("number like '%{0}%'", number);
                        }
                        // orderby 排序拼接
                        Ob ob = new Ob();
                        ob.Desc("create_time");
                        if (req_excel)
                        {
                            DataTable dt = GetSqlResult<ServiceItem>(cd.Render(), ob.Render()).FirstTable;
                            ResponseExcel(dt, ServiceItem.ExcelColumns);
                        }
                        else
                        {
                            ResponseJson(GetPageResult<ServiceItem>(cd.Render(), ob.Render()));
                        }
                        return;
                    }
                case "get":
                    {
                        ServiceItem service = G.DB.GetById<ServiceItem>(req_id);
                        service.view_times++;
                        G.DB.Update<ServiceItem>(service);
                        ResponseJson(new ObjectResult { data = service });
                        return;
                    }
            }

            CheckPermission(IDENTITY.MEMBER);
            switch (action)
            {
                case "create":
                    {
                        string now = DateTimeEx.GetNowTimeStamp();
                        ServiceItem service = new ServiceItem {
                            status = (int)SERVICE_STATUS.DRAFT,
                            title = req_title,
                            member_id = UserCode,
                            create_time = now,
                            is_delete = (int)SERVICE_ISDELETE.ALIVE,
                            number = "sv" + now + UserCode
                        };
                        G.DB.Insert<ServiceItem>(service);
                        ResponseJson(new IDResult { id = service.id });
                        break;
                    }
                case "draft":
                    {
                        ServiceItem service = new ServiceItem { status = (int)SERVICE_STATUS.DRAFT };
                        ApplyDataToService(service);
                        G.DB.Insert<ServiceItem>(service);
                        ResponseJson(new IDResult { id = service.id });
                        break;
                    }
                case "recycle":
                    {
                        ServiceItem service = G.DB.GetById<ServiceItem>(req_id);
                        service.status = (int)SERVICE_STATUS.RECLAIMED;
                        G.DB.Update<ServiceItem>(service);
                        ResponseJson(new Result());
                        break;
                    }
                case "post":
                    {
                        ServiceItem service = G.DB.GetById<ServiceItem>(req_id);
                        ApplyDataToService(service);
                        service.status = FreeValue.GetValue("check.open_check", "1") == "1" ? (int)SERVICE_STATUS.EXAMINING : (int)SERVICE_STATUS.POSTED;
                        G.DB.Update<ServiceItem>(service);
                        ResponseJson(new ValueResult { value = service.status });
                        break;
                    }
                case "re_draft":
                    {
                        ServiceItem service = G.DB.GetById<ServiceItem>(req_id);
                        ApplyDataToService(service);
                        service.status = (int)SERVICE_STATUS.DRAFT;
                        G.DB.Update<ServiceItem>(service);
                        ResponseJson(new Result());
                        break;
                    }
                case "delete":
                    {
                        if (G.DB.Delete<ServiceItem>(req_id) == 0) { ThrowStatus(STATUS.FAILED_DELETE, "删除失败！"); }
                        ResponseJson(new Result());
                        break;
                    }
                    //新添加文本相似度推荐系统
                case "title_recommend":
                    {
                        string name = GetStringParam(new ReqStringParamOption { Name = "name", Level = REQPARAMLEVEL.FREE });
                        Cd cd = new Cd();
                        Ob ob = new Ob();
                        if (name != "")
                        {
                            cd.And("title like '%{0}%'", name);
                        }
                        cd.And("member_id={0} and status = 2", UserCode);
                        ob.Desc("id");
                        SqlResult<ServiceItem> serviceItem = G.DB.Get<ServiceItem>(cd.Render(), ob.Render(), 10); //取最近前十条
                        List<ServiceItem> serviceList = serviceItem.GetFirstTableList();

                        SqlResult<DemandItem> demandItem = G.DB.Get<DemandItem>("status = 2");
                        List<DemandItem> demandList = demandItem.GetFirstTableList();

                        StringCompute stringcompute1 = new StringCompute();
                        List<MatchRate> title_list = new List<MatchRate>();
                        List<MatchRate> list = new List<MatchRate>();

                        for (int i = 0; i < serviceList.Count; i++)
                        {
                            decimal rate = 0;
                            List<MatchRate> ratelist = new List<MatchRate>();
                            for (int j = 0; j < demandList.Count; j++)
                            {
                                stringcompute1.SpeedyCompute(demandList[j].title, serviceList[i].title);    // 计算相似度， 不记录比较时间
                                rate = stringcompute1.ComputeResult.Rate;         // 相似度百分之几，完全匹配相似度为1
                                MatchRate match = new MatchRate();
                                match.matchid = serviceList[i].id;//当前服务/需求的id
                                match.match_title = serviceList[i].title;
                                match.rate = rate;//相似度
                                match.id = demandList[j].id;//当前服务/需求相似的需求/服务的id
                                match.title = demandList[j].title;
                                match.datetime = demandList[j].create_time;
                                match.content = demandList[j].demand_content;//当前服务相似的需求内容
                                match.match_content = serviceList[i].service_content;//当前服务内容
                                ratelist.Add(match);
                            }
                            List<MatchRate> matchList = stringcompute1.MergeSort1(ratelist, 0, ratelist.Count - 1).Take(ratelist.Count < 4 ? ratelist.Count : 4).ToList<MatchRate>(); //获得匹配结果列表,按rate排序
                            title_list.AddRange(matchList);
                        }
                        int current_page = req_current_page;
                        int page_size = req_page_size;
                        int total = title_list.Count;
                        list = (title_list.Skip((current_page - 1) * page_size).Take(page_size).ToList<MatchRate>());
                        ResponseJson(new PageResult<MatchRate> { page = new PageData<MatchRate> { current_page = current_page, page_size = page_size, total = total, list = list } });
                        break;
                    }

                //新添加推荐系统
                case "recommend":
                    {
                        // condition 条件拼接
                        string area = GetStringParam(new ReqStringParamOption { Name = "area", Level = REQPARAMLEVEL.FREE });
                        bool view_time = GetBooleanParam(new ReqBooleanParamOption { Name = "view_time", Level = REQPARAMLEVEL.FREE });
                        bool create_time = GetBooleanParam(new ReqBooleanParamOption { Name = "create_time", Level = REQPARAMLEVEL.FREE });
                        bool type = GetBooleanParam(new ReqBooleanParamOption { Name = "type", Level = REQPARAMLEVEL.FREE });
                        bool title = GetBooleanParam(new ReqBooleanParamOption { Name = "title", Level = REQPARAMLEVEL.FREE });
                        Cd cd = new Cd();
                        Ob ob = new Ob();
                        if (UserRole == (int)ROLE_TYPES.SERVICE)
                        {
                            if (area != "" && area != "[]")
                            {
                                area = area.Replace("\"", "");
                                area = area.Replace("[", "");
                                area = area.Replace("]", "");
                                area = area.Split(',')[0];
                                cd.And("area like '%{0}%' and role_type = 4", area);
                                ob.Desc("id");
                                SqlResult<DemandItem> demand = null;
                                List<DemandItem> lists = new List<DemandItem>();
                                List<List<DemandItem>> demandList = new List<List<DemandItem>>();
                                SqlResult<Member> member = G.DB.Get<Member>(cd.Render(), ob.Render(), 10);
                                List<Member> memberList = member.GetFirstTableList<Member>();
                                foreach (var item in memberList)
                                {
                                    string str = string.Format("member_id ={0} and status = 2", item.id.ToString());
                                    demand = G.DB.Get<DemandItem>(str);
                                    lists = demand.GetFirstTableList();
                                    if (lists.Count != 0)
                                    {
                                        demandList.Add(lists);
                                    }
                                }
                                if (demandList.Count == 0)
                                {
                                    Cd cd1 = new Cd();
                                    Ob ob1 = new Ob();
                                    ob1.Desc("id");
                                    demand = G.DB.Get<DemandItem>(cd1.Render(), ob1.Render(), 10);
                                    lists = demand.GetFirstTableList();
                                    if (lists.Count != 0)
                                    {
                                        demandList.Add(lists);
                                    }
                                }
                                ResponseJson(new ListResult<List<DemandItem>> { list = demandList }, "id,title,demand_content");
                            }
                            else if (view_time)
                            {
                                ob.Desc("view_times");
                                SqlResult<DemandItem> demandItem = G.DB.Get<DemandItem>(cd.Render(), ob.Render(), 20);
                                List<DemandItem> demandList = demandItem.GetFirstTableList();
                                ResponseJson(new ListResult<DemandItem> { list = demandList }, "id,title,demand_content");
                            }
                            else if (create_time)
                            {
                                ob.Desc("create_time");
                                SqlResult<DemandItem> demandItem = G.DB.Get<DemandItem>(cd.Render(), ob.Render(), 20);
                                List<DemandItem> demandList = demandItem.GetFirstTableList();
                                ResponseJson(new ListResult<DemandItem> { list = demandList }, "id,title,demand_content");
                            }
                            else if (type)
                            {
                                cd.And("member_id={0}", UserCode);
                                ob.Desc("id");
                                SqlResult<ServiceItem> serviceItem = G.DB.Get<ServiceItem>(cd.Render(), ob.Render(), 10);
                                List<ServiceItem> serviceList = serviceItem.GetFirstTableList();
                                List<string> servicetype = new List<string>();
                                for (int i = 0, len = serviceList.Count; i < len; i++)
                                {
                                    if (serviceList[i].service_type != null && !servicetype.Contains(serviceList[i].service_type))
                                    {
                                        servicetype.Add(serviceList[i].service_type);
                                    }
                                }
                                SqlResult<DemandItem> demandItem = G.DB.Get<DemandItem>();
                                List<DemandItem> demandList = demandItem.GetFirstTableList();
                                List<DemandItem> item = new List<DemandItem>();
                                for (int i = 0, len = demandList.Count; i < len; i++)
                                {
                                    if (servicetype.Contains(demandList[i].demand_type))
                                    {
                                        item.Add(demandList[i]);
                                    }
                                }
                                if (item.Count == 0)
                                {
                                    Cd cd1 = new Cd();
                                    Ob ob1 = new Ob();
                                    ob1.Desc("id");
                                    demandItem = G.DB.Get<DemandItem>(cd1.Render(), ob1.Render(), 10);
                                    item = demandItem.GetFirstTableList();
                                }
                                ResponseJson(new ListResult<DemandItem> { list = item }, "id,title,demand_content");
                            }
                            else
                            {
                                ResponseJson(new ValueResult { value = "noarea" });
                            }
                        }
                        else
                        {
                            if (area != "" && area != "[]")
                            {
                                area = area.Replace("\"", "");
                                area = area.Replace("[", "");
                                area = area.Replace("]", "");
                                area = area.Split(',')[0];
                                cd.And("area like '%{0}%' and role_type = 5", area);
                                ob.Desc("id");
                                SqlResult<ServiceItem> service = null;
                                List<ServiceItem> lists = new List<ServiceItem>();
                                SqlResult<Member> member = G.DB.Get<Member>(cd.Render(), ob.Render());
                                List<Member> memberList = member.GetFirstTableList<Member>();
                                List<List<ServiceItem>> serviceList = new List<List<ServiceItem>>();
                                foreach (var item in memberList)
                                {
                                    string str = string.Format("member_id ={0} and status = 2", item.id.ToString());
                                    service = G.DB.Get<ServiceItem>(str);
                                    lists = service.GetFirstTableList();
                                    if (lists.Count != 0)
                                    {
                                        serviceList.Add(lists);
                                    }
                                }
                                if (serviceList.Count == 0)
                                {
                                    Cd cd1 = new Cd();
                                    Ob ob1 = new Ob();
                                    ob1.Desc("id");
                                    service = G.DB.Get<ServiceItem>(cd1.Render(), ob1.Render(), 10);
                                    lists = service.GetFirstTableList();
                                    if (lists.Count != 0)
                                    {
                                        serviceList.Add(lists);
                                    }
                                }
                                ResponseJson(new ListResult<List<ServiceItem>> { list = serviceList }, "id,title,service_content");
                            }
                            else if (view_time)
                            {
                                ob.Desc("view_times");
                                SqlResult<ServiceItem> serviceItem = G.DB.Get<ServiceItem>(cd.Render(), ob.Render(), 20);
                                List<ServiceItem> serviceList = serviceItem.GetFirstTableList();
                                ResponseJson(new ListResult<ServiceItem> { list = serviceList }, "id,title,service_content");
                            }
                            else if (create_time)
                            {
                                ob.Desc("create_time");
                                SqlResult<ServiceItem> serviceItem = G.DB.Get<ServiceItem>(cd.Render(), ob.Render(), 20);
                                List<ServiceItem> serviceList = serviceItem.GetFirstTableList();
                                ResponseJson(new ListResult<ServiceItem> { list = serviceList }, "id,title,service_content");
                            }
                            else if (type)
                            {
                                cd.And("member_id={0}", UserCode);
                                ob.Desc("id");
                                SqlResult<DemandItem> demandItem = G.DB.Get<DemandItem>(cd.Render(), ob.Render(), 10);
                                List<DemandItem> demandList = demandItem.GetFirstTableList();
                                List<string> demandtype = new List<string>();
                                for (int i = 0, len = demandList.Count; i < len; i++)
                                {
                                    if (demandList[i].demand_type != null && !demandtype.Contains(demandList[i].demand_type))
                                    {
                                        demandtype.Add(demandList[i].demand_type);
                                    }
                                }
                                SqlResult<ServiceItem> serviceItem = G.DB.Get<ServiceItem>();
                                List<ServiceItem> serviceList = serviceItem.GetFirstTableList();
                                List<ServiceItem> item = new List<ServiceItem>();
                                for (int i = 0, len = serviceList.Count; i < len; i++)
                                {
                                    if (demandtype.Contains(serviceList[i].service_type))
                                    {
                                        item.Add(serviceList[i]);
                                    }
                                }
                                if (item.Count == 0)
                                {
                                    Cd cd1 = new Cd();
                                    Ob ob1 = new Ob();
                                    ob1.Desc("id");
                                    serviceItem = G.DB.Get<ServiceItem>(cd1.Render(), ob1.Render(), 10);
                                    item = serviceItem.GetFirstTableList();
                                }
                                ResponseJson(new ListResult<ServiceItem> { list = item }, "id,title,service_content");
        
                            }
       
                            else
                            {
                                ResponseJson(new ValueResult { value = "noarea" });
                            }
                        }
                        break;
                    }
                    default: break;
            }
        }

        private ServiceItem ApplyDataToService(ServiceItem obj)
        {
            obj.title = req_title;
            obj.member_id = UserCode;
            obj.m_type = GetStringParam(new ReqStringParamOption { Name = "m_type" });
            obj.service_type = GetStringParam(new ReqStringParamOption { Name = "service_type" });
            obj.service_content = GetStringParam(new ReqStringParamOption { Name = "service_content" });
            obj.service_people = GetStringParam(new ReqStringParamOption { Name = "service_people" });
            obj.requirement = GetStringParam(new ReqStringParamOption { Name = "requirement" });
            obj.service_feature = GetStringParam(new ReqStringParamOption { Name = "service_feature" });
            obj.service_department = GetStringParam(new ReqStringParamOption { Name = "service_department" });
            obj.service_master = GetStringParam(new ReqStringParamOption { Name = "service_master" });
            obj.service_tele = GetStringParam(new ReqStringParamOption { Name = "service_tele" });
            obj.service_address = GetStringParam(new ReqStringParamOption { Name = "service_address" });
            obj.approve_time = GetStringParam(new ReqStringParamOption { Name = "approve_time" });
            obj.finish_time = GetStringParam(new ReqStringParamOption { Name = "finish_time" });
            obj.needFileds = GetStringParam(new ReqStringParamOption { Name = "needFileds" });
            obj.Remark = GetStringParam(new ReqStringParamOption { Name = "Remark" });
            obj.appendix_ids = GetStringParam(new ReqStringParamOption { Name = "appendix_ids" });
            obj.create_time = DateTimeEx.GetNowTimeStamp();
            return obj;
        }
    }

    enum SERVICE_STATUS
    {
        DRAFT = 0, // 草稿
        EXAMINING = 1, // 正在审核
        POSTED = 2, // 已发布
        FAILED_EXAMINE = 3, // 审核失败
        RECLAIMED = 4, // 已回收
    }
    enum SERVICE_ISDELETE
    {
        ALIVE = 0,//未删除
        DELETE = 1//已删除
    }
}